package controller;

import com.alibaba.fastjson.JSONObject;
import utils.UserManager;
import utils.MD5UsingMessageDigest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class Register extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        JSONObject resJson = new JSONObject();
        UserManager userManager = new UserManager();

        try {
            if (password.length() < 6) {
                resJson.put("status", "error");
                resJson.put("message", "密码长度不能少于6位");
            } else if (userManager.userExists(email)) {
                resJson.put("status", "error");
                resJson.put("message", "用户已存在");
            } else {
                String passwordMD5 = MD5UsingMessageDigest.md5(password);
                userManager.registerUser(username, email, passwordMD5);
                resJson.put("status", "success");
                resJson.put("message", "注册成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resJson.put("status", "error");
            resJson.put("message", "服务器错误");
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(resJson.toJSONString());
    }
}